var express = require('express');
var router = express.Router();
var path = require('path');
var SqliteDB = require('sqlite3').verbose();

var nodemailer = require("nodemailer");
var smtpTransport = require('nodemailer-smtp-transport');
var settingConfig = require('../config/settingConfig.js');//解析参数

var smtp = settingConfig["smtp"];
//var mailFrom = Buffer.from(settingConfig["mailFrom"]).toString('base64');
//var mailPwd = Buffer.from(settingConfig["mailPwd"]).toString('base64');
var mailFrom = settingConfig["mailFrom"];
var mailPwd = settingConfig["mailPwd"];
 
function emailTo(email,subject,text,html,callback) {
// 开启一个 SMTP 连接池
    var transporter = nodemailer.createTransport(smtpTransport({
        host: smtp,//主机
        secure: true, // 使用 SSL
        secureConnection: true, // 使用 SSL
        port: 465, // SMTP 端口
        auth: {
            type:'login',
            user: mailFrom,
            pass: mailPwd //授权码,通过QQ获取  

        }
    }));
    var mailOptions = {
        from: mailFrom, // 发送者  
        to: email, // 接受者,可以同时发送多个,以逗号隔开  
        subject: subject, // 标题  
    };    
    mailOptions.text =text;// 文本  30 
    var result = {
        httpCode: 200,
        message: '发送成功!',
        data: [],
    }
    try {
        transporter.sendMail(mailOptions, function (err, info) {
            if (err) {
                result.httpCode = 500;
                result.message = err;
                callback(result);
                return;
            }
            callback(result);
        });
        //transport || transport.close(); // 如果没用，关闭连接池
    } catch (err) {
        result.httpCode = 500;
        result.message = err;
        callback(result);
    }
    
}

/* GET users listing. */
router.get('/', function(req, res, next) {
var username = req.query['username'];
var password = req.query['password'];
var sql = "select email from user where username='"+ username +"' and password='"+password + "'";
var db = new SqliteDB.Database(path.join(__dirname + '/../db/aiattendance.s3db'));
var re = '1';
db.serialize(function(){
    db.get(sql, function(){
    if(arguments.length>=2){      
        var data = arguments[1];
        if(data['email']){
            var x = Math.ceil(Math.random()*1000000);
            req.session['x'] = x;
            emailTo(data['email'],"验证码", x,function(data){
                res.status(data.httpCode).json(data);
              })
            re = '0';
            req.session["username"] = username;
        }
    }
    res.send(re);
    })
});  
db.close();  


  
  //res.send('respond with a resource');
});

module.exports = router;
